import $http from '@/shopro/request/index'
// #ifdef H5
import wxsdk from '@/shopro/wechat/sdk'
// #endif
import wechat from '@/shopro/wechat/wechat'
import {
	router as $Router
} from '@/shopro/router/index.js'
import store from '@/shopro/store';
import $platform from '@/shopro/platform';


export default class ShoproPay {


	//						wxOfficialAccount			wxMiniProgram			App						H5
	// 			wechat			公众号JSSDK支付				小程序支付			微信开放平台支付			H5网页支付
	//			alipay			复制网址						复制网址				支付宝开放平台支付		    直接跳转链接
	// 			wallet			v							v					v						v


	constructor(payment, order, paypwd = null) {
		this.payment = payment;
		this.order = order;
		this.paypwd = paypwd
		this.pay_type = order.pay_type;
		this.platform = $platform.get();
		
		// console.log(this.platform);return;
		const payArr = payment.split('-');
		if (payArr.length === 2) this.joinPay(payArr[1]);
		else {
			let payMehod = this.getPayMethod();
			payMehod();
		}
	}

	getPayMethod() {
		var payMethod = {
			'wxOfficialAccount': {
				'wechat': () => {
					this.wxOfficialAccountPay()
				},
				'alipay': () => {
					this.copyPayLink()
				},
				'wallet': () => {
					this.walletPay()
				},
				'delivery_card': () => {
					this.deliveryCardPay()
				}
			},
			'wxMiniProgram': {
				'wechat': () => {
					this.wxMiniProgramPay()
				},
				'alipay': () => {
					this.copyPayLink()
				},
				'wallet': () => {
					this.walletPay()
				},
			},
			'App': {
				'wechat': () => {
					this.wechatPay()
				},
				'alipay': () => {
					this.aliPay()
				},
				'wallet': () => {
					this.walletPay()
				},
			},
			'H5': {
				'wechat': () => {
					this.wechatWapPay()
				},
				'alipay': () => {
					this.goToPayLink()
				},
				'wallet': () => {
					this.walletPay()
				},
				'delivery_card': () => {
					this.deliveryCardPay()
				}
			},
		}
		return payMethod[this.platform][this.payment];
	}



	// 预支付
	prepay(terminal = '') {
		let that = this;
		return new Promise((resolve, reject) => {
			let that = this;
			let params = {
				order_sn: that.order.order_sn,
				payment: that.payment,
				paypwd: that.paypwd,
				pay_type:this.pay_type,
				terminal
			}
			if (uni.getStorageSync('openid')) {
				params.openid = uni.getStorageSync('openid');
			}
			$http('money.prepay', params, '支付中').then(res => {
				if (res.code === 1) {
					// console.log(this.platform);return;
					if(this.platform == "h5"){
							uni.showLoading({
								title: "请使用微信浏览器支付"
							})
							return;
					}else{
						res.data === 'no_openid' ?
							uni.showModal({
								title: '微信支付',
								content: '请先绑定微信再使用微信支付',
								success: function(res) {
									if (res.confirm) {
										wechat.bind();
									}
								},
							}) :
							resolve(res);
					}
				}else{
					if(res.code == 0){
						uni.showLoading({
							title: res.msg
						})
						return;
					}
					that.towpayResult('success');
				}
			})
		});
	}


	// 微信公众号支付
	async wxOfficialAccountPay() {
		let that = this;
		let result = await this.prepay('wechat');
		wxsdk.wxpay(result.data.pay_data, (res) => {
			res.errMsg == "chooseWXPay:ok" ? that.payResult('success') : that.payResult('fail')
		});

	}

	//浏览器微信支付
	async wechatWapPay() {
		let that = this;
		let result = await this.prepay('wechat');
		if (result.code === 1) {
			var url = result.data.pay_data.match(/url\=\'(\S*)\'/);
			let reg = new RegExp('&amp;', 'g') //g代表全部
			let newUrl = url[1].replace(reg, '&');
			let domain = store.state.shopro.config.shop.domain; //域名需要https
			let params = encodeURIComponent(
				`${domain}pages/order/payment/result?orderId=${that.order.id}&type=${that.payment}`)
			window.location.href = newUrl + '&redirect_url=' + params;
		}
	}

	// 微信小程序支付
	async wxMiniProgramPay() {
		let that = this;
		let result = await this.prepay();
		uni.requestPayment({
			provider: 'wxpay',
			...result.data.pay_data,
			success: res => {
				that.payResult('success')
			},
			fail: err => {
				console.log('支付取消或者失败:', err);
				err.errMsg !== "requestPayment:fail cancel" && that.payResult('fail')
			}
		});
	}

	// 余额支付
	async walletPay() {
		let that = this;
		let result = await this.prepay();
		// console.log(result.code);return;
		if(result.code === 1){
			that.payResult('success')
		}else{
			that.towpayResult('success');
		}
	}
	
	// 提货卡支付
	async deliveryCardPay() {
		let that = this;
		let result = await this.prepay();
		result.code === 1 && that.payResult('success')
	}

	// 支付宝复制链接支付
	async copyPayLink() {
		let that = this;
		let result = await this.prepay();
		if (result.code === 1) {
			//引入showModal 点击确认 复制链接；
			uni.navigateTo({
				url: '/pages/order/payment/alipay?url=' + btoa(result.data.pay_data)
			})
			/*uni.showModal({
				title: '支付宝支付',
				content: '复制链接到外部浏览器',
				confirmText: '复制链接',
				success: (res) => {
					if (res.confirm) {
						uni.setClipboardData({
							data: result.data.pay_data,
							success: function(data) {
								that.$u.toast('已复制到剪切板');
							}
						});
					}
				}
			})*/
		}
	}

	// 支付链接
	async goToPayLink() {
		let that = this;
		let result = await this.prepay();
		if (result.code === 1) {
			window.location = result.data.pay_data;
		}
	}

	// 支付宝支付
	async aliPay() {
		let that = this;
		let result = await this.prepay();
		if (result.code === 1) {
			uni.requestPayment({
				provider: 'alipay',
				orderInfo: result.data.pay_data, //支付宝订单数据
				success: res => {
					that.payResult('success')
				},
				fail: err => {
					console.log('支付取消或者失败:', err);
					err.errMsg !== "requestPayment:fail cancel" && that.payResult('fail')
				}
			});
		}
	}

	// 微信支付
	async wechatPay() {
		let that = this;
		let result = await this.prepay('wechat');
		if (result.code === 1) {
			uni.requestPayment({
				provider: 'wxpay',
				orderInfo: JSON.parse(result.data.pay_data), //微信订单数据(官方说是string。实测为object)
				success: res => {
					that.payResult('success')
				},
				fail: err => {
					err.errMsg !== "requestPayment:fail cancel" && that.payResult('fail')
					console.log('支付取消或者失败:', err);
				}
			});
		}
	}


	// 支付结果跳转,success:成功，fail:失败
	payResult(resultType) {
		const that = this;
		$Router.replace({
			path: '/pages/order/payment/result',
			query: {
				orderId: that.order.id,
				type: that.payment, //重新支付的时候使用
				payState: resultType
			}
		});
	}
	
	towpayResult(resultType) {
		const that = this;
		$Router.replace({
			path: '/pages/index/user',
			query: {
				orderId: that.order.id,
				type: that.payment, //重新支付的时候使用
				payState: resultType
			}
		});
	}


	// 汇聚支付
	async joinPay(channel) {
		const codeList = {
			wxOfficialAccount: {
				wx: 'WEIXIN_GZH',
				ali: 'ALIPAY_H5'
			},
			wxMiniProgram: {
				wx: 'WEIXIN_XCX'
			},
			App: {
				wx: 'WEIXIN_APP',
				ali: 'ALIPAY_APP'
			},
			H5: {
				wx: 'WEIXIN_H5_PLUS',
				ali: 'ALIPAY_H5'
			}
		}
		const type = codeList[this.platform][channel];
		const params = {
			order_sn: this.order.order_sn,
			type: codeList[this.platform][channel],
		}
		const res = await $http('money.joinpay', params);
		const data = res.data;
		if (data === 'no_openid') {
			uni.showModal({
				title: '微信支付',
				content: '请先绑定微信再使用微信支付',
				success: function(res) {
					if (res.confirm) {
						wechat.bind();
					}
				},
			})
			return;
		}

		switch (this.platform) {
			case 'wxOfficialAccount':
				switch (channel) {
					case 'wx':
						wxsdk.wxpay(JSON.parse(data), res => {
							res.errMsg == "chooseWXPay:ok" ? this.payResult('success') : this.payResult(
								'fail')
						});
						break;
					case 'ali':
						const matchList = data.match(/location.href='(.*?)'/);
						uni.navigateTo({
							url: '/pages/order/payment/alipay?url=' + btoa(matchList[1])
						})
						break;
				}
				break;

			case 'wxMiniProgram':
				uni.showToast({icon:'none', title:data})
				console.log('暂不支持')
				break;
			case 'App':
				uni.showToast({icon:'none', title:data})
				console.log('暂不支持')
				break;
			case 'H5':
				switch (channel) {
					case 'wx':
						uni.showToast({icon:'none', title:data})
						console.log('暂不支持')
						break;
					case 'ali':
						const matchList = data.match(/location.href='(.*?)'/);
						window.location.href = matchList[1];
						break;
				}
				break;
		}
	}
}
